#include <bits/stdc++.h>
// 2025/06/09
// tag:
// Author: Forever
using namespace std;
using int64 = int64_t;

const int N = 100001;
int flag;
int n, l[N], r[N], f[N][2];

int dfs(int u, int deep)
{
    if (l[u] == -1 && r[u] == -1) {
        f[u][0] = deep, f[u][1] = deep;
        return 0;
    }
    int swaps = 0;

    if (l[u] == -1) {
        swaps += dfs(r[u], deep + 1) + 1;
        f[u][0] = deep, f[u][1] = f[r[u]][1];
    } else if (r[u] == -1) {
        swaps += dfs(l[u], deep + 1);
        f[u][0] = deep, f[u][1] = f[l[u]][1];
    } else {
        swaps += dfs(l[u], deep + 1);
        swaps += dfs(r[u], deep + 1);
        bool canNormal = (f[l[u]][0] >= f[r[u]][1]);
        bool canSwap = (f[r[u]][0] >= f[l[u]][1]);
        if (!canNormal && !canSwap) {
            flag = 1;
        } else if (!canNormal && canSwap) {
            swaps++;
        }
        f[u][0] = min(f[l[u]][0], f[r[u]][0]);
        f[u][1] = max(f[l[u]][1], f[r[u]][1]);
    }

    return swaps;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> l[i] >> r[i];

    flag = 0;
    int ans = dfs(1, 1);

    if (f[1][1] - f[1][0] > 1 || flag)
        cout << -1 << endl;
    else
        cout << ans << endl;
    return 0;
}